#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
import re
from datetime import datetime
from config import load_config,save_config
from ifaddr_ipv6 import get_global_ipv6
from mail import postEmail
import requests
from werkzeug.utils import secure_filename
import tempfile


app = Flask(__name__, static_folder='static', static_url_path='')
CORS(app)  # 允许跨域请求



@app.route('/')
def index():
    """首页 - 返回Vue应用"""
    return send_from_directory('static', 'index.html')

@app.route('/webdav')
def webdav_page():
    """WebDAV文件上传页面"""
    return send_from_directory('static', 'webdav_upload.html')

@app.route('/api/webdav/upload', methods=['POST'])
def webdav_upload_api():
    """WebDAV文件上传API"""
    try:
        # 获取WebDAV配置
        webdav_url = request.form.get('webdav_url')
        webdav_user = request.form.get('webdav_user')
        webdav_pass = request.form.get('webdav_pass')
        
        # 获取上传的文件
        file = request.files.get('file')
        if not file:
            return jsonify({
                'success': False,
                'message': '未收到文件'
            })
        
        # 验证WebDAV配置
        if not all([webdav_url, webdav_user, webdav_pass]):
            return jsonify({
                'success': False,
                'message': 'WebDAV配置不完整'
            })
        
        # 安全处理文件名
        filename = secure_filename(file.filename)
        
        # 创建临时文件保存上传的文件内容
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_path = temp_file.name
            file.save(temp_path)
        
        # 构建WebDAV目标URL
        if not webdav_url.endswith('/'):
            webdav_url += '/'
        target_url = webdav_url + filename
        
        # 上传到WebDAV服务器
        headers = {
            'Content-Type': 'application/octet-stream'
        }
        
        with open(temp_path, 'rb') as f:
            response = requests.put(
                target_url,
                auth=(webdav_user, webdav_pass),
                headers=headers,
                data=f,
                timeout=300  # 5分钟超时
            )
        
        # 删除临时文件
        os.unlink(temp_path)
        
        # 检查上传结果
        if 200 <= response.status_code < 300:
            return jsonify({
                'success': True,
                'message': '文件上传成功',
                'filename': filename,
                'url': target_url
            })
        else:
            return jsonify({
                'success': False,
                'message': f'WebDAV服务器错误: {response.status_code} - {response.reason}'
            })
            
    except Exception as e:
        print(f"WebDAV上传错误: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'上传失败: {str(e)}'
        })



@app.route('/api/ip6', methods=['GET'])
def get_ip_api():
    """获取配置信息"""
    ip6 = get_global_ipv6()
    if ip6:
        return jsonify({
            'success': True,
            'data': ip6
        })
    return jsonify({
        'success': False,
        'data': "未获取到全局IP6"
    })

@app.route('/api/send_email', methods=['POST'])
def send_email_api():
    data = request.get_json()
    email = data.get('email', "")
    email_send = data.get('email_send', "")
    email_send_pd = data.get('email_send_pd', "")
    res=postEmail("测试文本",email,email_send,email_send_pd)
    return jsonify({
        'success': res[0],
        'data': "发送成功" if res[0] else res[1]
    })

@app.route('/api/domain_resolution', methods=['POST'])
def resolution_api():
    print("11")
    return jsonify({
        'success': True,
        'data': "发送成功"
    })



@app.route('/api/config', methods=['GET'])
def get_config_api():
    """获取配置信息"""
    config = load_config()
    if config:
        # 隐藏敏感信息
        safe_config = config.copy()
        return jsonify({
            'success': True,
            'data': safe_config
        })
    return jsonify({
        'success': True,
        'data': {}
    })



@app.route('/api/config', methods=['POST'])
def save_config_api():
    # """保存配置信息"""
    try:
        data = request.get_json()
        data["created_at"]=datetime.now().isoformat()
        print(data)
        if save_config(data):
            return jsonify({
                'success': True,
                'message': '配置保存成功！'
            })
        else:
            return jsonify({
                'success': False,
                'message': '配置保存失败！'
            })

    except Exception as e:
        print(e)
        return jsonify({
            'success': False,
            'message': f'服务器错误: {str(e)}'
        })


def main():
    print("🚀 启动Flask应用...")
    print("📍 访问地址: http://localhost:9550")
    print("🛑 按 Ctrl+C 停止服务器")
    app.run(host='0.0.0.0', port=9550, debug=True)


if __name__ == '__main__':
    main()
    # save_config({"aa":1})
